package com.spyu.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日期工具类
 *
 * @author spyu
 * @date 2023-03-08
 */
public final class DateUtils {

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 将LocalDateTime时间转换格式为pattern的字符串
     *
     * @param time
     * @param pattern
     * @return
     */
    public static String convertLocalDateTimeToStr(LocalDateTime time, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        return time.format(dtf);
    }

    /**
     * 将格式为pattern的字符串转换为LocalDateTime时间
     *
     * @param timeStr
     * @param pattern
     * @return
     */
    public static LocalDateTime convertStrToLocalDateTime(String timeStr, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(timeStr, dtf);
    }

    /**
     * 将LocalDate时间转换格式为pattern的字符串
     *
     * @param time
     * @param pattern
     * @return
     */
    public static String convertLocalDateToStr(LocalDate time, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        return time.format(dtf);
    }

    /**
     * 将格式为pattern的字符串转换为LocalDateTime时间
     *
     * @param timeStr
     * @param pattern
     * @return
     */
    public static LocalDate convertStrToLocalDate(String timeStr, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(timeStr, dtf);
    }

    /**
     * 获取格式为yyyy-MM-dd的日期字符串
     *
     * @return
     */
    public static String getCurrentDate() {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_PATTERN);
        return currentTime.format(dtf);
    }

    /**
     * 获取格式为yyyy-MM-dd HH:mm:ss的日期时间字符串
     *
     * @return
     */
    public static String getCurrentDateTime() {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
        return currentTime.format(dtf);
    }

    /**
     * 将当前时间转换为指定格式的字符串
     *
     * @param pattern
     * @return
     */
    public static String convertCurrentDateTimeForPattern(String pattern) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        return currentTime.format(dtf);
    }

}
